<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jquery 成绩查询</title>
    <style>
        table,
        th,
        td {
            border: 1px solid;
        }
    </style>
</head>

<body>
    <h1>成绩查询</h1>
    <div>
        <input type="text" placeholder="请输入学生 id">
        <input type="button" value="查询">
    </div>

    <h1>查询结果</h1>
    <table>
        <thead>
            <tr>
                <th>成绩</th>
                <th>姓名</th>
                <th>等级</th>
            </tr>
        </thead>
        <tbody id='result_tbody'></tbody>
    </table>

    <h1>学生列表</h1>
    <table>
        <thead>
            <tr>
                <th>学号</th>
                <th>姓名</th>
                <th>成绩</th>
            </tr>
        </thead>
        <tbody id='list_tbody'></tbody>
    </table>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/Mock.js/1.0.1-beta3/mock-min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
    <script>
        let students = Mock.mock({
            'list|20': [{
                'id|+1': 1,
                'score|0-100': 1,
                'name': '@cname()'
            }]
        }).list;

        var compiled = _.template(`<% _.forEach(students, function(user) { 
            %>
                <tr>
                    <td><%- user.id %></td>
                    <td><%- user.name %></td>
                    <td><%- user.score %></td>
                </tr>
            <% 
            }); %>`);
        let str = compiled();
        $('#list_tbody').html(str);

        // 按钮
        $('[type="button"]').click(function () {
            let id = $('[type="text"]').val();
            let student = _.find(students, function (o) { return o.id == id; });
            if (student) {
                let lev = '';
                if (student.score > 90) {
                    lev = 'A';
                } else if (student.score > 70) {
                    lev = 'B';
                } else {
                    lev = 'C';
                }
                $('#result_tbody').html(`
                    <tr>
                        <td>${student.score}</td>    
                        <td>${student.name}</td>    
                        <td>${lev}</td>    
                    </tr>
                `);
            } else {
                $('#result_tbody').html(`<tr><td colspan='3'>查无此人</td>`);
            }
        });

    </script>
</body>

</html>